<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\controller\Abnormal;
use app\admin\model\Marking;
use app\admin\model\Street;
use app\admin\model\User;

/**
 * 基类服务
 * @author 牧羊人
 * @since 2020/11/19
 * Class BaseService
 * @package app\admin\service
 */
class BaseService
{
    // 模型
    protected $model;
    protected $name;
    protected $model_type;

    /**
     * 获取数据列表
     * @return array
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function getList()
    {
        // 初始化变量
        $map = [];
        $sort = 'id desc';
        $is_sql = 0;

        // 获取参数
        $argList = func_get_args();
        if (!empty($argList)) {
            // 查询条件
            $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
            // 排序
            $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'id desc';
            // 是否打印SQL
            $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        }

        // 常规查询条件
        $param = request()->param();
        if ($param) {
            // 筛选名称
            if (isset($param['name']) && $param['name']) {
                $map[] = ['name', 'like', "%{$param['name']}%"];
            }

            // 筛选标题
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 筛选类型
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }

            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }

            // 手机号码
            if (isset($param['mobile']) && $param['mobile']) {
                $map[] = ['mobile', '=', $param['mobile']];
            }
        }

        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $result = $this->model->where($map)->order($sort)->page(PAGE, PERPAGE)->column("id");

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val);
                $list[] = $info;
            }
        }

        //获取数据总数
        $count = $this->model->where($map)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }

    /**
     * 获取记录详情
     * @return array
     * @since 2020/11/15
     * @author 牧羊人
     */
    public function info()
    {
        // 记录ID
        $id = request()->param("id", 0);
        $info = [];
        if ($id) {
            $info = $this->model->getInfo($id);
        }
        return message("操作成功", true, $info);
    }
    public function getLog(){
        $operation_no =  request()->param("operation_no", 0);
        $time = request()->param('create_time',[]);

        $operation_category = request()->param('operation_category',0);
        $exception_category = request()->param('exception_category',0);
        $address_detailed = trim(request()->param('address_detailed',''));
        $model_type = $this->model_type;
        $markModel = new Marking();
        $list = $markModel->with(['user'])
            ->where(function ($query)use($time,$exception_category,$operation_category,$operation_no,$address_detailed,$model_type){
                if($model_type){
                    $query->where(['model_type'=>$model_type]);
                }
                if($address_detailed){
                    $query->where(['address_detailed'=>$address_detailed]);
                }
                if($operation_no){
                    $query->where(['operation_no'=>$operation_no]);
                }
                if($time){
                    $start_time = strtotime($time[0]);
                    $end_time = strtotime($time[1]) + 60*60*24-1;
                    $query->whereBetween('create_time',[$start_time,$end_time]);
                }
                if($exception_category){
                    $query->where('exception_category',$exception_category);
                }
                if($operation_category){
                    $query->where('operation_category',$operation_category);
                }
            })->order('exception_category asc,id desc')->select();
        $adminModel = new User();
        $Abnormal = new \app\admin\model\Abnormal();
        foreach ($list as $key => &$value){
            $value['area_id'] = [
                (substr($value['area_id'], 0, 2) . '0000'),
                (substr($value['area_id'], 0, 4) . '00'),
                (string)$value['area_id']
            ];
//        return $Abnormal->where(['id'=>$data['exception_category']])->value('name');
            $value['exception_category_name'] =$Abnormal->where(['id'=>$value['exception_category']])->value('name');
            $value['shenhe'] = $adminModel->whereIn('id',$value['shen_ids'])->field('id,realname')->select();
            $value['images_arr'] = empty($value['images']) ? [] : json_decode($value['images'],true);
        }
        return message("操作成功", true, $list);
    }
    /**
     * 添加或编辑
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function edit()
    {
        // 获取参数
        $argList = func_get_args();
        // 查询条件
        $data = isset($argList[0]) ? $argList[0] : [];
        // 是否打印SQL
        $is_sql = isset($argList[1]) ? $argList[1] : false;
        if (!$data) {
            $data = request()->param();
        }
        $markingModel = new Marking();

        if(isset($data['address'])){
            $address_detailed = $data['address'];
        }
        if(isset($data['id']) && isset($data['address']) && !isset($data['log_id'])){

            $info =  $this->model->get($data['id']);
            $data['address'] = $info['address'] ? $info['address'].','.$data['address'] : $data['address'];
        }
        if(isset($data['log_id'])){
            $address = $markingModel->where(['operation_no'=>$data['operation_no']])->whereNotIn('id',$data['log_id'])->column('address_detailed');
            $detailed = '';
            foreach ($address as $key => $val){
                if($key == 0){
                    $detailed = $val;
                }else{
                    $detailed = $detailed.",".$val;
                }
            }
            $data['address'] = $detailed;
        }
        $error = '';
        $rowId = $this->model->edit($data, $error, $is_sql);
        if ($rowId) {
            if($this->name){
                $streetModel = new Street();
                $street = $streetModel->getInfoByGrid($data['longitude'],$data['latitude']);
                $newdata = [
                    'operation_no'=>$data['operation_no'],
                    'organization_id'=>$data['organization_id'],
                    'operation_category'=>$data['operation_category'],
                    'exception_category'=>$data['exception_category'],
                    'area_id'=>$data['area_id'],
                    'street'=>$data['street'],
                    'address'=>$address_detailed,
                    'address_detailed'=>trim($address_detailed),
                    'model_type'=>$this->model_type,
                    'longitude'=>isset($data['longitude']) ?$data['longitude'] : '',
                    'latitude'=>isset($data['latitude']) ?$data['latitude'] : '',
                    'shen_ids'=>isset($data['shen_ids']) ?$data['shen_ids']  : '',
                    'images'=>isset($data['images']) ? $data['images']  : '',
                    'street_id'=> $street['id']
                ];
                // log_id 打标记录id   id 作业记录id
                if(($data['id'] && isset($data['log_id']) && !empty($data['log_id'])) || (isset($data['id'])&& empty($data['id']))){
                    if($data['log_id'] && $data['id']){
                        $newdata['id'] = $data['log_id'];
                    }
                    $markingModel->edit($newdata);
                }
            }
            return message();
        }
        return message($error, false);
    }

    /**
     * 删除记录
     * @return array
     * @since 2020/11/12
     * @author 牧羊人
     */
    public function delete()
    {
        // 参数
        $param = request()->param();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }
        if (is_array($ids)) {
            // 批量删除
            $result = $this->model->deleteDAll($ids);
            if (!$result) {
                return message("删除失败", false);
            }
            return message("删除成功");
        } else {
            // 单个删除
            $info = $this->model->getInfo($ids);
            if ($info) {
                $result = $this->model->drop($ids);
                if ($result !== false) {
                    return message();
                }
            }
            return message($this->model->getError(), false);
        }
    }

    /**
     * 设置状态
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function status()
    {
        $data = request()->param();
        if (!$data['id']) {
            return message('记录ID不能为空', false);
        }
        if (!$data['status']) {
            return message('记录状态不能为空', false);
        }
        $error = '';
        $item = [
            'id' => $data['id'],
            'status' => $data['status']
        ];
        $rowId = $this->model->edit($item, $error);
        if (!$rowId) {
            return message($error, false);
        }
        return message();
    }
    public function getOperationNo(){
        $start_time  = strtotime(date('Y-m-d',time()));
        $end_time = $start_time + 60*60*24-1;
        $oper_no = $this->name . date('Y',time()) . date('m',time()).date("d",time());
        $num = $this->model->whereBetween('create_time',[$start_time,$end_time])->count();
        $num = str_pad($num+1,4,'0',STR_PAD_LEFT);
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $oper_no.$num,
        );
        return $message;
    }
}